﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02创建图形
{
    public class DrawFile
    {
        [CommandMethod("DrawDemo")]
        public void DrawDemo()
        {
            Database db = HostApplicationServices.WorkingDatabase;

            //定义文件名
            string fileName = @"E:\AutoCAD 二次开发\AutoCAD C#.Net 二次开发 视频教程 基础篇\测试文件\输气管道主线拐点-一海结果.txt";
            //把文件内容读取到数组
            string[] contents = File.ReadAllLines(fileName);
            //声明List对象,将数据进行整理
            List<List<string>> List = new List<List<string>>();
            for (int i = 0; i < contents.Length; i++)
            {
                string[] cont = contents[i].Split(new char[] { ' ' });
                List<string> subList = new List<string>();
                for (int j = 0; j < cont.Length; j++)
                {
                    subList.Add(cont[j]);
                }
                List.Add(subList);
            }

            //声明多段线对象
            Polyline pLine = new Polyline();
            for (int i = 0; i < List.Count; i++)
            {
                //数据转换
                double X, Y;
                bool bx = double.TryParse(List[i][0], out X);
                bool by = double.TryParse(List[i][1], out Y);
                //如果外部文件出错,给用户提示
                if (by == false || bx == false)
                {
                    Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
                    ed.WriteMessage("外部文件有错误!,绘制图形失败!");
                    return;
                }
                pLine.AddVertexAt(i, new Point2d(X, Y),0,0,0);
            }
            db.AddEnityToModelSpace(pLine);
        }
    }
}
